package com.woniuxy.hotel.setting.util;
import freemarker.cache.FileTemplateLoader;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import com.itextpdf.text.FontProvider;
import com.woniuxy.hotel.setting.util.FontProviderImp;
import org.w3c.tidy.Tidy;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import java.io.*;
import java.util.Map;


/**
 * @Auther: desk-----xuzhiliang
 * @Date: 2019/8/9 17:02
 * @Description:
 */
public class TranslateUtil {

    /**
     * 通过路径 和文件名称后去魔板
     *
     * @param templateFilePath
     * @param templateFileName
     * @return
     */
    public static Template getTemplate(String templateFilePath, String templateFileName) {
        try {
            Configuration cfg = new Configuration();
            cfg.setClassicCompatible(true);

            TemplateLoader templateLoader = new FileTemplateLoader(new File(
                    templateFilePath));
            cfg.setTemplateLoader(templateLoader);
            return cfg.getTemplate(templateFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param html
     * @param xhtml
     * @Description 翻译后的模板转xhtml
     * @Param * @param null
     * @Return
     * @Author desk-----xuzhiliang
     * @Date 2019/8/9
     * @Time 17:08
     */

    public static String html2Xhtml(String html, String xhtml) {
        String path = null;
        try {
            FileInputStream fin = new FileInputStream(html);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            int data = -1;
            while ((data = fin.read()) != -1) {
                byteArrayOut.write(data);
            }
            fin.close();
            byte[] htmlFileData = byteArrayOut.toByteArray();

            byteArrayOut.close();

            ByteArrayInputStream tidyInput = new ByteArrayInputStream(
                    htmlFileData);
            ByteArrayOutputStream tidyOut = new ByteArrayOutputStream();
            Tidy tidy = new Tidy();
            tidy.setInputEncoding("UTF-8");
            tidy.setOutputEncoding("UTF-8");
            tidy.setShowWarnings(false);
            tidy.setIndentContent(true);
            tidy.setSmartIndent(true);
            tidy.setIndentAttributes(false);
            tidy.setMakeClean(true);
            tidy.setQuiet(true);
            tidy.setWord2000(true);
            tidy.setXHTML(true);
            tidy.setErrout(new PrintWriter(System.out));

            tidy.parse(tidyInput, tidyOut);
            tidyInput.close();
            tidyOut.writeTo(new FileOutputStream(xhtml));
            tidyOut.flush();
            tidyOut.close();
            path = xhtml;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            path = null;
        } catch (IOException e) {
            e.printStackTrace();
            path = null;
        }
        return path;
    }

    /**
     * @param xhtml
     * @param pdf
     * @Description xhtml转pdf
     * @Param * @param null
     * @Return
     * @Author desk-----xuzhiliang
     * @Date 2019/8/9
     * @Time 17:10
     */

    public static void XHtml2Pdf(String xhtml, String pdf) throws Exception{
        if (xhtml != null) {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(pdf));
            document.open();
            FontProvider fontProvider = new FontProviderImp();
//            fontProvider.addFontSubstitute("lowagie", "garamond");
//            fontProvider.setUseUnicode(true);
            // 使用我们的字体提供器，并将其设置为unicode字体样式
            CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(
                    cssAppliers);
            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
            CSSResolver cssResolver = XMLWorkerHelper.getInstance()
                    .getDefaultCssResolver(true);
            Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,
                    new HtmlPipeline(htmlContext, new PdfWriterPipeline(
                            document, writer)));
            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser p = new XMLParser(worker);

            File input = new File(xhtml);
            p.parse(new InputStreamReader(new FileInputStream(input), "UTF-8"));
            document.close();
        }


    }

    /**
     * @param templateFilePath 加载的模板路径
     * @param templateFileName 加载的模板文件名
     * @param replaceData
     * @param outFile          生成指定文件
     * @return 文件名
     */

    public static Writer freemarkToHtml(String templateFilePath, String templateFileName, Map<String, Object> replaceData,
                                 String outFile) {

        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile), "UTF-8"));
            Template temp = getTemplate(templateFilePath, templateFileName);
            temp.setOutputEncoding("UTF-8");
            //执行翻译转化
            temp.process(replaceData, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out;
    }
}
